package collector

import (
	"github.com/prometheus/common/log"
	"github.com/rancher/go-rancher/v2"
	"time"
)

func StartRancherEvent(conf Config) error {

	err := conf.EnvironmentURL()
	if err != nil {
		log.Error(err)
		return err
	}

	opts := client.ClientOpts{
		Url:       conf.WsUrl,
		AccessKey: conf.AccessKey,
		SecretKey: conf.SecretKey,
	}
	reconnect := true
	for {
		c, err := client.NewRancherClient(&opts)
		if err != nil {
			log.Error(err)
			time.Sleep(time.Second)
			continue
		}
		m := New(c)
		sub := m.Subscribe()

		go func() {
			if reconnect {
				for {
					if err := m.Start(); err != nil {
						log.Error(err)
					}
					time.Sleep(time.Second)
				}
			} else {
				log.Fatal(m.Start())
			}
		}()
		for event := range sub.C {
			re := new(RancherEvent)
			err = re.Event(event, conf)
			if err != nil {
				log.Error(err)
			}
		}
	}
}
